﻿using System;
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using TUNING;
using KMod;
using STRINGS;
using Newtonsoft.Json;
using UnityEngine;
using System.Reflection;

namespace HelloWorldNameSpace
{
    public class HelloWorld : UserMod2
    {
        public static string pathToConfig;

        public static HelloWorld.Config config;


        public override void OnLoad(Harmony harmony)
        {
            try
            {
                base.OnLoad(harmony);
                Global.Instance.modManager.NotifyDialog("Hello .", "Mod Hello World. Loaded.", Global.Instance.globalCanvas);

                HelloWorld.AnnouncePatches();
                global::Debug.Log("[HelloWorld] [OnLoad] HelloWorld.dll!");
                global::Debug.Log(string.Concat(new object[]
                    {
                        "Hello World . This is super999. SKILLS.ACTIVE_EXPERIENCE_PORTION:",
                        SKILLS.ACTIVE_EXPERIENCE_PORTION,
                        " FULL_EXPERIENCE:",
                        DUPLICANTSTATS.ATTRIBUTE_LEVELING.FULL_EXPERIENCE
                    }));
                int factor = 5;
                SKILLS.ACTIVE_EXPERIENCE_PORTION = 30f;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.FULL_EXPERIENCE = 100f * factor;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.ALL_DAY_EXPERIENCE = 100f * factor;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.FULL_EXPERIENCE = 100f * factor;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.MOST_DAY_EXPERIENCE = 80f * factor;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.PART_DAY_EXPERIENCE = 25f * factor;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.BARELY_EVER_EXPERIENCE = 10f * factor;
                DUPLICANTSTATS.ATTRIBUTE_LEVELING.MAX_GAINED_ATTRIBUTE_LEVEL = 5000;
                SKILLS.FULL_EXPERIENCE = 100f * factor;
                SKILLS.ALL_DAY_EXPERIENCE = 100f * factor;
                SKILLS.FULL_EXPERIENCE = 100f * factor;
                SKILLS.MOST_DAY_EXPERIENCE = 80f * factor;
                SKILLS.PART_DAY_EXPERIENCE = 25f * factor;
                SKILLS.BARELY_EVER_EXPERIENCE = 10f * factor;
                /*Storage.capacityKg = 20000f;*/
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                throw ex;
            }
        }

/*        public static void PrePatch(Harmony harmony)
        {
            string text = Path.Combine(Manager.GetDirectory(), Path.Combine("settings", "HelloWorld"));
            if (!Directory.Exists(text))
            {
                Directory.CreateDirectory(text);
            }
            HelloWorld.pathToConfig = Path.Combine(text, "config.json");
            HelloWorld.LoadConfig();
        }*/

/*        private static void LoadConfig()
        {
            if (File.Exists(HelloWorld.pathToConfig))
            {
                global::Debug.Log("[HelloWorld] Loading config.json");
                HelloWorld.config = JsonConvert.DeserializeObject<HelloWorld.Config>(File.ReadAllText(HelloWorld.pathToConfig));
                if (HelloWorld.config.version == 4)
                {
                    return;
                }
            }
            else
            {
                global::Debug.Log("[HelloWorld] Creating config.json");
                HelloWorld.config = new HelloWorld.Config();
            }
            HelloWorld.config.version = 4;
            HelloWorld.config.name = "Me";
            File.WriteAllText(HelloWorld.pathToConfig, JsonConvert.SerializeObject(HelloWorld.config, Formatting.Indented));
            Application.OpenURL(Path.GetDirectoryName(HelloWorld.pathToConfig));
        }*/

        public static void AnnouncePatches()
        {
            global::Debug.Log("[HelloWorld] Announce harmony patches");
            Type[] types = Assembly.GetExecutingAssembly().GetTypes();
            for (int i = 0; i < types.Length; i++)
            {
                global::Debug.Log("[HelloWorld]" + types[i].FullName);
                /* foreach (HarmonyMethod harmonyMethod in types[i].GetHarmonyMethods())
                 {
                     global::Debug.Log("[HelloWorld] -> " + harmonyMethod.declaringType.FullName + "." + harmonyMethod.methodName);
                 }*/
            }
        }

        public class Config
        {
            public string name;

            public int version;
        }

        [HarmonyPatch(typeof(Battery))]
        [HarmonyPatch("OnSpawn")]
        public static class Battery_OnSpawn_Patch
        {
            internal static void Postfix(Battery __instance)
            {
                Building component = __instance.GetComponent<Building>();
                if (!component)
                {
                    return;
                }
                string prefabID = component.Def.PrefabID;
                try
                {
                    if (!(prefabID == "PowerTransformer") && !(prefabID == "PowerTransformerSmall"))
                    {
                        component.Def.SelfHeatKilowattsWhenActive = 0.1f;
                    }
                }
                catch (Exception ex)
                {
                    Debug.Log("[HelloWorld] " + prefabID + " - " + ex.Message);
                    Debug.LogException(ex);
                }
            }
        }

        [HarmonyPatch(typeof(AirFilter))]
        [HarmonyPatch("OnSpawn")]
        public static class AirFilter_OnSpawn_Patch
        {
            public static void Postfix(AirFilter __instance)
            {
                //                 ElementConverter component = __instance.GetComponent<ElementConverter>();
                // 
                //                 if (!component)
                //                 {
                //                     return;
                //                 }
                //                 try
                //                 {
                //                     ElementConverter.OutputElement clay = component.outputElements[0];
                //                     ElementConverter.OutputElement oxygen = component.outputElements[1];
                //                     clay.massGenerationRate = clay.massGenerationRate * 100.0f;
                //                     oxygen.massGenerationRate = oxygen.massGenerationRate * 100.0f;
                // 
                //                     ElementConverter.ConsumedElement filter = component.consumedElements[0];
                //                     ElementConverter.ConsumedElement ContaminatedOxygen = component.consumedElements[0];
                //                     filter.massConsumptionRate = filter.massConsumptionRate * 50.0f;
                //                     ContaminatedOxygen.massConsumptionRate = ContaminatedOxygen.massConsumptionRate * 100.0f;
                //                 }
                //                 catch (Exception ex)
                //                 {
                //                     Debug.Log("[HelloWorld] " + " - " + ex.Message);
                //                     Debug.LogException(ex);
                //                 }
            }
        }

        [HarmonyPatch(typeof(Telepad))]
        [HarmonyPatch("RejectAll")]
        public static class Telepad_RejectAll_Patch
        {
            public static void Postfix(Telepad __instance)
            {
                Immigration.Instance.timeBeforeSpawn = 2.0f;
            }
        }

        [HarmonyPatch(typeof(Storage))]
        [HarmonyPatch("OnSpawn")]
        public static class Storage_OnSpawn_Patch
        {
            internal static void Postfix(Storage __instance)
            {
                /*global::Debug.Log("[HelloWorld] SAtorage_OnSpawn_Patch Postfix " + __instance.name + " " + __instance.capacityKg);*/
                if(__instance.name.IndexOf("Atmo_Suit")!=-1)
                {
                    global::Debug.Log("[HelloWorld] SAtorage_OnSpawn_Patch Postfix Skip 0 " + __instance.name);
                    return;
                }
                if (__instance.name.IndexOf("Suit")!=-1)
                {
                    global::Debug.Log("[HelloWorld] SAtorage_OnSpawn_Patch Postfix Skip 1 " + __instance.name);
                    return;
                }
                if (__instance.name.IndexOf("Atmo")!= -1)
                {
                    global::Debug.Log("[HelloWorld] SAtorage_OnSpawn_Patch Postfix Skip 2 " + __instance.name);
                    return;
                }
                if (__instance.name.IndexOf("GasBottler") != -1)
                {
                    global::Debug.Log("[HelloWorld] SAtorage_OnSpawn_Patch Postfix Skip 3 " + __instance.name);
                    return;
                }
                if (__instance.name.IndexOf("Sink") != -1)
                {
                    global::Debug.Log("[HelloWorld] SAtorage_OnSpawn_Patch Postfix Skip 4 " + __instance.name);
                    return;
                }
                bool bFind = false;
                if (__instance.name.IndexOf("StorageLocker") != -1)
                {
                    bFind = true;
                }
                if (__instance.name.IndexOf("Sink") != -1)
                {
                    bFind = true;
                }
                if (__instance.name.IndexOf("LiquidReservoir") != -1)
                {
                    bFind = true;
                }
                if (__instance.name.IndexOf("GasReservoir") != -1)
                {
                    bFind = true;
                }

                if(!bFind)
                {
                    global::Debug.Log("[HelloWorld] skip " + __instance.name);
                    return;
                }
                global::Debug.Log("[HelloWorld] ready hack " + __instance.name);
                Building component = __instance.GetComponent<Building>();

                if (!component)
                {
                    return;
                }
                string prefabID = component.Def.PrefabID;
                try
                {
                    float new_cap = __instance.capacityKg * 50;
                    __instance.capacityKg = new_cap;
                    /* IUserControlledCapacity component2 = __instance.GetComponent<IUserControlledCapacity>();
                     if (component2 != null)
                     {
                         __instance.capacityKg = num2;
                         component2.UserMaxCapa city = new_cap;
                     }
                    */
                    ConduitConsumer component3 = __instance.GetComponent<ConduitConsumer>();
                    if (component3 != null)
                    {
                        component3.capacityKG = new_cap;
                    }

                }
                catch (NullReferenceException ex)
                {
                    global::Debug.Log("[HelloWorld] " + prefabID + " - " + ex.Message);
                    global::Debug.LogException(ex);
                }
                catch (Exception ex)
                {
                    global::Debug.Log("[HelloWorld] " + prefabID + " - " + ex.Message);
                    global::Debug.LogException(ex);

                }
/*                catch
                {
                    global::Debug.Log("[HelloWorld] unknow exception.");
                }*/
            }
        }
    }
}
